#include "tablescorewidget.h"
#include <QDebug>

TableScoreWidget::TableScoreWidget(QWidget* parent) : QTableWidget(parent)
{

}

void TableScoreWidget::addRow(QString nick, qint16 score)
{
    int rc = rowCount();
    setRowCount(rc+1);
    QTableWidgetItem *vhead = new QTableWidgetItem();
    vhead->setData(Qt::DisplayRole, QVariant(rc+1));
    setVerticalHeaderItem(rc, vhead);
    QTableWidgetItem *n = new QTableWidgetItem(nick);
    setItem(rc, 0, n);
    QTableWidgetItem *s = new QTableWidgetItem();
    s->setData(Qt::DisplayRole, QVariant(score));
    setItem(rc, 1, s);
    sortByColumn(1,Qt::DescendingOrder);
}

void TableScoreWidget::addPlayer(ConnectionPlayer* player)
{
    quint8 id = player->getPlayerId();
    foreach (ConnectionPlayer* p, playerList)
    {
        if (p->getPlayerId() == id) return;
    }
    playerList.append(player);
    addRow(player->getNick(), player->getScore());
}

void TableScoreWidget::removePlayer(ConnectionPlayer* player)
{
    qint32 count = playerList.count();
    for (int i = 0; i < count; i++)
    {
        removeRow(0);
    }
    playerList.remove(playerList.indexOf(player));
    updateTable();
}

void TableScoreWidget::removePlayerById(qint32 id)
{
    foreach (ConnectionPlayer* player, playerList)
    {
        if (player->getPlayerId() == id)
        {
            removePlayer(player);
            return;
        }
    }
}

void TableScoreWidget::clearPlayers()
{
    qint32 count = playerList.count();
    for (int i = 0; i < count; i++)
    {
        removeRow(0);
    }
    playerList.clear();
}

void TableScoreWidget::updateTable()
{
    qint32 count = playerList.count();
    for (int i = 0; i < count; i++)
    {
        removeRow(0);
    }
    for (int i = 0; i < playerList.count(); i++)
    {
        addRow(playerList.at(i)->getNick(),playerList.at(i)->getScore());
    }
}


